package models

import (
	"fmt"
)

//用户基础表
type User struct {
	*BaseModel
	Username string `json:"name" gorm:"name"`
	Gender   int    `json:"gender" gorm:"gender"`
	OpenId   string `json:"openid" gorm:"openid"`
	Unionid  string `json:"unionid" gorm:"unionid"`
	Nickname string `json:"nickname" gorm:"nickname"`
	Avatar   string `json:"avatar" gorm:"avatar"`
	Province string `json:"province" gorm:"province"`
	County   string `json:"county" gorm:"county"`
	City     string `json:"city" gorm:"city"`
	Address  string `json:"address" gorm:"address"`
	Phone    string `json:"phone" gorm:"phone"`
}

type WechatLoginReq struct {
	EncryptedData string      `json:"encryptedData" form:"encryptedData"`
	Iv            string      `json:"iv" form:"iv"`
	SessionId     string      `json:"session_id" form:"session_id"`
	UserInfo      UserInfoReq `json:"user_info" form:"user_info"`
}
type UserInfoReq struct {
	NickName  string `json:"nickName" form:"nickName"`
	AvatarUrl string `json:"avatarUrl" form:"avatarUrl"`
	Gender    int    `json:"gender" form:"gender"`
	Country   string `json:"country" form:"country"`
	Province  string `json:"province" form:"province"`
	City      string `json:"city" form:"city"`
	Language  string `json:"language" form:"language"`
	OpenId    string `json:"openid" form:"openid"`
}

func (t User) TableName() string {
	return "blog_tag"
}
func (u User) Create() error {
	return DBEngine.Create(&u).Error
}

func (u User) List(page, pageSize int) error {
	var list []User
	db := DBEngine
	if page >= 0 && pageSize >= 0 {
		db = db.Limit(pageSize).Offset(page)
	}
	if u.Nickname != "" {
		db = db.Where("nickname like %?%", u.Nickname)
	}
	return db.Find(&list).Error
}

func (u User) Update() error {
	return DBEngine.Where("id = ?", u.ID).Updates(&u).Error
}

//更新或者创建用户
func (u *User) UpdateOrCreateUser() error {

	user := User{}
	res := DBEngine.Where("openid = ?", u.OpenId).First(&user)
	fmt.Println(user)
	//如果没有就创建用户
	if user.ID == 0 {
		res = DBEngine.Create(&u)
		if res.Error != nil {
			return res.Error
		}
		return nil
	}
	//如果存在就更新用户
	res = DBEngine.Model(&user).Where("openid = ?", u.OpenId).Updates(&u)
	if res.Error != nil {
		return res.Error
	}
	//更新成功获取user
	DBEngine.Model(&user).Where("openid = ?", u.OpenId).First(&u)
	return nil
}
